<?php

namespace App\Http\Controllers\User;

use App\Http\Requests\UserCreateRequest;
use App\Http\Requests\UserUpdateRequest;
use App\Http\Controllers\Controller;
use App\Models\Role;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
//use Maatwebsite\Excel\Facades\Excel;
//use Mail;
//use Hash;// 密码加密的明文是否是对应的

class UserController extends Controller
{
    /**
     * 显示用户列表.
     * @param Request $request
     */
    public function index(Request $request)
    {
        if($request->ajax()){
            $model = User::query();
            if ($request->get('username')){
                $model = $model->where('username','like','%'.$request->get('username').'%');
            }
            if ($request->get('phone')){
                $model = $model->where('phone','like','%'.$request->get('phone').'%');
            }
            if ($request->get('email')){
                $model = $model->where('email',$request->get('email'));
            }

            $res = $model->where('user_type', '0')->orderBy('created_at','desc')->paginate($request->get('limit',30))->toArray();
            $data = [
                'code' => 0,
                'msg'   => '正在请求中...',
                'count' => $res['total'],
                'data'  => $res['data']
            ];
            return response()->json($data);
        }

        return view('user.user.index');
    }

    /**
     * 创建新用户表单页面
     */
    public function create()
    {
        $provinceData = (new DistrictController)->province();
        return view('user.user.create', compact('provinceData'));
    }

    /**
     * 将新创建的用户存储到存储器
     * @param Request $request
     */
    public function store(UserCreateRequest $request)
    {
        $data = $request->all();
        $data['password'] = bcrypt($data['password']);
        $data['uuid'] = \Faker\Provider\Uuid::uuid();
        if (User::create($data)){
            // 发邮件给用户
//        Mail::send('mail.useradd',compact('userModel','$data['password']'),function (Message $message) use ($userModel){
//            // 发给谁
//            $message->to($userModel->email);
//            // 主题
//            $message->subject('开通账号箱件通知');
//        });
            return redirect()->to(route('admin.user'))->with(['status'=>'添加账号成功']);
        }
        return redirect()->to(route('admin.user'))->withErrors('系统错误');
    }

    /**
     * 显示指定文章
     *
     * @param int $id
     * @return Response
     */
    public function show($id)
    {
        //
    }

    /**
     * 显示编辑指定用户的表单页面
     *
     * @param int $id
     * @return \Illuminate\View\View
     */
    public function edit($id)
    {
        $user = User::find($id);
        return view('user.user.edit',compact('user'));
    }

    /**
     * 在存储器中更新指定文章
     *
     * @param Request $request
     * @param int $id
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    public function update(UserUpdateRequest $request, $id)
    {
        $member = User::findOrFail($id);
        $data = $request->except('password');
        if ($request->get('password')){
            $data['password'] = bcrypt($request->get('password'));
        }
        if ($member->update($data)){
            return redirect()->to(route('admin.member'))->with(['status'=>'更新用户成功']);
        }
        return redirect()->to(route('admin.member'))->withErrors('系统错误');

        $model = User::find($id);
        // 原密码  明文
        $spass = $request->get('spassword');
        // 原密码 密文
        $oldpass = $model->password;
        // 检查明文和密码是否一致
        $bool = Hash::check($spass,$oldpass);
        if($bool){
            // 修改
            $data = $request->only([
                'name',
                'password',
                'phone',
                'sex',
                'email'
            ]);
            if(!empty($data['password'])){
                $data['password'] = bcrypt($data['password']);
            }else{
                unset($data['password']);
            }
            $model->update($data);
            return redirect(route('admin.user.index'))->with(['status'=>'更新用户成功']);
        }
        return redirect(route('admin.user.edit',$model))->withErrors('系统错误');
    }

    /**
     * 从存储器中移除指定文章
     *
     * @param int $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function destroy(Request $request)
    {
        $ids = $request->get('ids');
        if (empty($ids)){
            return response()->json(['code'=>1,'msg'=>'请选择删除项']);
        }
        if (User::destroy($ids)){
            return response()->json(['code'=>0,'msg'=>'删除成功']);
        }
        return response()->json(['code'=>1,'msg'=>'删除失败']);
    }

    // 还原
    public function restore(int $id) {
        // 还原 只显示已删除的数据
        User::onlyTrashed()->where('id',$id)->restore();
        return redirect(route('admin.user.index'))->with('success','还原成功');
    }

    // 导出excel
    public function exports() {
        $data = User::collection();
        return Excel::download($data, 'user.xlsx');
    }
}
